package com.shengyijie.activity.tab.user;
  

import org.apache.http.HttpResponse;

import com.shengyijie.activity.MainActivity;
import com.shengyijie.activity.R;        
import com.shengyijie.activity.commen.ItemActivity;
import com.shengyijie.context.ContextApplication;
import com.shengyijie.model.database.dataoperate.AccountInfoDB;
import com.shengyijie.model.http.HttpConnectApi;
import com.shengyijie.model.json.JsonParser; 
import com.shengyijie.util.Utility;

import android.app.Activity; 
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener; 
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class RegisterActivity extends Activity implements OnClickListener{ 
	  
	 private ImageButton tabHome;
	 private ImageButton tabCategory;
	 private ImageButton tabRecommended;
	 private ImageButton tabUser;
	 private ImageButton tabMore;
	 private Button register; 
	 private CheckBox article;
	 
	 private TextView tv_article;
	 
	 private LinearLayout L_name;
	 private LinearLayout property;
	 private LinearLayout linkman;
	 
	 private Spinner property1;
	 private Spinner property2;
	 
	 private EditText et_email;
	 private EditText et_name;
	 private EditText et_mobile;
	 private EditText et_password;
	 private EditText et_password2; 
	 private EditText et_contacter; 
	 
	 private String email;
	 private String name;
	 private String mobile;
	 private String password;
	 private String password2; 
	 private String contacter;
	 
	 private int user_type=0;
	 private int industry=0;
	 private int com_type=0;
	
	private RadioGroup radioGroup; 
	
	public Task task;
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState); 
         requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
         setContentView(R.layout.register);
         getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,      // 注意顺序
                 R.layout.title);
         initView();
         initSpinner();
         ContextApplication.USER_TYPE=0;
    } 
    
    public void initView(){ 
    	register=(Button) this.findViewById(R.id.register);
    	register.setOnClickListener(this);
    	
    	article=(CheckBox) this.findViewById(R.id.article);
    	article.setOnClickListener(this);
    	
    	tv_article=(TextView) this.findViewById(R.id.ta);
    	tv_article.setOnClickListener(this);
    	
    	property1=(Spinner) this.findViewById(R.id.property1);
    	property2=(Spinner) this.findViewById(R.id.property2);
    	 
    	
    	radioGroup=(RadioGroup) this.findViewById(R.id.group);
    	radioGroup.setOnCheckedChangeListener(changeRadio);
    	
    	L_name=(LinearLayout) this.findViewById(R.id.lname);
    	property=(LinearLayout) this.findViewById(R.id.property);
    	linkman=(LinearLayout) this.findViewById(R.id.llinkman);
    	
    	L_name.setVisibility(View.GONE);
 	    property.setVisibility(View.GONE);
 	    linkman.setVisibility(View.GONE);
    	
    	TextView title=(TextView) this.findViewById(R.id.title);
		title.setText("注册新用户"); 
		
		Button back=(Button) this.findViewById(R.id.back);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		
		
		 et_email=(EditText) this.findViewById(R.id.email);
		 et_name=(EditText) this.findViewById(R.id.name);
		 et_mobile=(EditText) this.findViewById(R.id.tel);
		 et_password=(EditText) this.findViewById(R.id.passwd);
		 et_password2=(EditText) this.findViewById(R.id.passwd1); 
		 et_contacter=(EditText) this.findViewById(R.id.linkman);
		 //et_user_type=(EditText) this.findViewById(R.id.title);
    	
    	
    	tabHome=(ImageButton) this.findViewById(R.id.home);
    	tabCategory=(ImageButton) this.findViewById(R.id.category);
    	tabRecommended=(ImageButton) this.findViewById(R.id.recommended);
    	tabUser=(ImageButton) this.findViewById(R.id.user);
    	tabMore=(ImageButton) this.findViewById(R.id.more);
		try{
		    switch(ContextApplication.prePage){
		       case ContextApplication.PAGE_HOME:
		    	   tabHome.setSelected(true);
			       break;
		       case ContextApplication.PAGE_CATEGORY:
		    	   tabCategory.setSelected(true);
			       break;
		       case ContextApplication.PAGE_RECOMMENDED:
		    	   tabRecommended.setSelected(true);
			       break;
		       case ContextApplication.PAGE_USER:
		    	   tabUser.setSelected(true);
			       break;
		       case ContextApplication.PAGE_MORE:
		    	   tabMore.setSelected(true);
			       break;
		     }
		 }catch(Exception e){}
		
		 tabHome.setOnClickListener(this);
		 tabCategory.setOnClickListener(this);
		 tabRecommended.setOnClickListener(this);
		 tabUser.setOnClickListener(this);
		 tabMore.setOnClickListener(this);
		 
		 
		 mypDialog=new ProgressDialog(this); 
	     mypDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
	     mypDialog.setIndeterminate(false); 
	     mypDialog.setCancelable(false); 
	     mypDialog.setOnKeyListener(new DialogOnKeyListener());
    }
    
    public class DialogOnKeyListener implements OnKeyListener {
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				try{
				  mypDialog.hide();
				  if(task.getStatus()==AsyncTask.Status.RUNNING){
		    		 task.cancel(true); 
				  }
			    }catch(Exception e){}
			 }
			return true;
		}
    }
    
    public void initSpinner(){
    	 String[] industrys={"外资企业","国有企业","私营企业","个人经营","事业单位"};
    	 String[] com_types={"服饰箱包","美容保健","美酒饮料","家居环保","餐饮娱乐","教育培训","新锐创意"};
   
    	 ArrayAdapter<String> adapter1=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, industrys);  
    	 ArrayAdapter<String> adapter2=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, com_types);  
    	 
    	 adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	 adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	 
    	 property1.setAdapter(adapter1);    
    	 property2.setAdapter(adapter2);   
    	 
    	 property1.setPrompt( " 请选择企业性质 ： " );
    	 property2.setPrompt( " 请选择主营行业 ： " ); 
    	 
    	 property1.setOnItemSelectedListener(new OnItemSelectedListener() {
	            public void onItemSelected(AdapterView<?> parent,
	                View view,int position,long id) { 
	            		industry=position+1; 
	                }
	            public void onNothingSelected(AdapterView<?> parent) {
	            }
	                
	        });
    	 
    	 property2.setOnItemSelectedListener(new OnItemSelectedListener() {
	            public void onItemSelected(AdapterView<?> parent,
	                View view,int position,long id) { 
	            	   com_type=position+1; 
	                }
	            public void onNothingSelected(AdapterView<?> parent) {
	            }
	                
	        });
    }
    
    
    
    private RadioGroup.OnCheckedChangeListener changeRadio = new 
            RadioGroup.OnCheckedChangeListener()
   { 
     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId)
     { 
	       // TODO Auto-generated method stub 
	       if(checkedId==R.id.personal)
	       {  
	    	   user_type=0;
	    	   L_name.setVisibility(View.GONE);
	    	   property.setVisibility(View.GONE);
	    	   linkman.setVisibility(View.GONE);
	    	   
	    	   ContextApplication.USER_TYPE=ContextApplication.USER_TYPE_PERSONAL;
	       } 
	       else if(checkedId==R.id.enterprise) 
	       {  
	    	   L_name.setVisibility(View.VISIBLE);
	    	   property.setVisibility(View.VISIBLE);
	    	   linkman.setVisibility(View.VISIBLE);
	    	   user_type=1;
	    	   ContextApplication.USER_TYPE=ContextApplication.USER_TYPE_ENTERPRISE;
	       }       
     } 
   }; 
    
    
    
 
	
   public void changeToOKActivity(){ 
	     Intent i=new Intent();
		 i.setClass(this, RegisterOKActivity.class);
		 this.startActivityForResult(i, 1); 
   }
	
	public void onClick(View v) { 
		
		Bundle bd = new Bundle();
        bd.putString("state", "exit");	
        Intent it = new Intent();
        it.putExtras(bd);
        
		switch(v.getId()){
		       case R.id.register:
		    	   try{
		    		   email=et_email.getText().toString().trim();
		    		   name= et_name.getText().toString().trim();
		    		   mobile= et_mobile.getText().toString().trim();
		    		   password= et_password.getText().toString().trim();
		    		   password2= et_password2.getText().toString().trim();
		    		   contacter= et_contacter.getText().toString().trim();
		    		   if(email.equals("")){
						    Toast.makeText(this, "邮箱名不能为空", Toast.LENGTH_SHORT).show();
						    et_email.requestFocus();
					   }else if(!Utility.isEmail(email)){
			    		   Toast.makeText(RegisterActivity.this, "请填写正确的邮箱号", Toast.LENGTH_SHORT).show();	
			    		   et_email.requestFocus();
			    	   }else if(!mobile.equals("")&&!Utility.isMobile(mobile)){
			    		   Toast.makeText(RegisterActivity.this, "请填写正确的手机号", Toast.LENGTH_SHORT).show();	
			    		   et_mobile.requestFocus();
			    	   }else if(password.length()<6){
						    Toast.makeText(this, "密码不能少于6位", Toast.LENGTH_SHORT).show();
						    et_password.requestFocus();
					   }else if(!password.equals(password2)){
						    Toast.makeText(this, "两次输入的密码不相同", Toast.LENGTH_SHORT).show();
						    et_password2.requestFocus();
						    if(password.equals("")){
							    Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
							    et_password.requestFocus();
						    }
					   }else{
						   
						 task=new Task();
						 task.execute(TASK_REGISTER);
					   } 
		    	   }catch(Exception e){}
			      break;
			      
//		       case R.id.article:
//		    	      if(article.isChecked()){
//		    	    	  Intent i2=new Intent();
//					      i2.setClass(this, ArticleActivity.class);
//					      this.startActivityForResult(i2, 1);
//		    	      } 
//				      break;
		       case R.id.ta:
//		    	      if(article.isChecked()){
		    	    	  Intent i2=new Intent();
					      i2.setClass(this, ArticleActivity.class);
					      this.startActivityForResult(i2, 1);
//		    	      } 
				      break;
			
			   case R.id.home:
				    try{
					   if(ContextApplication.prePage!=ContextApplication.PAGE_HOME){
						   MainActivity.tabhost.setCurrentTab(0);
						   setResult(RESULT_OK, it); 
						   this.finish();
					   }
				    }catch(Exception e){}
				    break;
			     case R.id.category:
					    try{
						   if(ContextApplication.prePage!=ContextApplication.PAGE_CATEGORY){
							   MainActivity.tabhost.setCurrentTab(1);
							   setResult(RESULT_OK, it); 
							   this.finish();
						   }
					    }catch(Exception e){}
					    break;
			     case R.id.recommended:
					    try{
						   if(ContextApplication.prePage!=ContextApplication.PAGE_RECOMMENDED){
							   MainActivity.tabhost.setCurrentTab(2);
							   setResult(RESULT_OK, it); 
							   this.finish();
						   }
					    }catch(Exception e){}
					    break;
			     case R.id.user:
					    try{
						   if(ContextApplication.prePage!=ContextApplication.PAGE_USER){
							   MainActivity.tabhost.setCurrentTab(3);
							   setResult(RESULT_OK, it); 
							   this.finish();
						   }
					    }catch(Exception e){}
					    break;
			     case R.id.more:
					    try{
						   if(ContextApplication.prePage!=ContextApplication.PAGE_MORE){
							   MainActivity.tabhost.setCurrentTab(4);
							   setResult(RESULT_OK, it); 
							   this.finish();
						   }
					    }catch(Exception e){}
					    break; 
			     case R.id.back:
					    try{
						  this.finish();
					    }catch(Exception e){}
					    break;
		}
		
	}
	
	
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {		
		   if(requestCode==1){
				if (resultCode != RESULT_OK) {
					return;
				}
			   try{
			       String state = data.getStringExtra("state");
			       if(state.equals("exit")){
			    	   Bundle bd = new Bundle();
			           bd.putString("state", "exit");	
			           Intent it = new Intent();
			           it.putExtras(bd);
			           setResult(RESULT_OK, it); 
			    	   this.finish();
			       }
			   }
			   catch(Exception e){}
		   }
	 }
	 
	 
	 public String doRegiSter(){
	    	String result="register_fail";
	        HttpConnectApi httpConnect = HttpConnectApi.getInstance();
	        try { 
	            HttpResponse response=httpConnect.regiSter(email,password,mobile,name,
	            		contacter,industry,com_type,ContextApplication.USER_TYPE);
	            if (response.getStatusLine().getStatusCode() == 200)
				{ 
	           	    JsonParser jsonParser=JsonParser.getInstance();
	           	    ContextApplication.user=jsonParser.getRegister(response);
	             	 ContextApplication.user.setUser_name(name);
	           	    if(ContextApplication.user.getState()==ContextApplication.RESULT_CODE_OK){
	           	    	Utility.saveUserSession(this, 1);
	           	    	result="register_ok";
	           	    }else if(ContextApplication.user.getState()==ContextApplication.RESULT_CODE_1000){
	           	    	result="register_had";
	           	    }
				}
	            return result;
	        }catch (Exception e) {} 
			return result;
	 }
	    
	 
	 
	 private ProgressDialog mypDialog; 
	 private final static int ALERT_LOADING=1; 
	 private final static int RESULT_REGISTER_OK=2;
	 private final static int RESULT_REGISTER_FAIL=3;
	 private final static int RESULT_REGISTER_HAD=4; 
	    
	 private final static String TASK_REGISTER="register";   
	 private final Handler handler = new Handler(Looper.getMainLooper()) {
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			 	switch (msg.what) { 
				   case ALERT_LOADING:
					    mypDialog.setMessage("正在注册新用户...");
					    mypDialog.show();
					    break;
				   case RESULT_REGISTER_FAIL:
					    try{
					       mypDialog.hide(); 
					       Toast.makeText(RegisterActivity.this, "对不起，注册失败", Toast.LENGTH_SHORT).show();
					     }catch(Exception e){}
					     break;
				   case RESULT_REGISTER_HAD:
					    try{
						     mypDialog.hide();
						     Toast.makeText(RegisterActivity.this, "对不起，您的邮箱已经注册过", Toast.LENGTH_SHORT).show();
						     et_email.setText("");
						     et_email.requestFocus(); 
			 	         }catch(Exception e){}
					     break;  
                   case RESULT_REGISTER_OK:
                   	     try{
	                    	 mypDialog.hide(); 
	                    	 if(user_type==1)
	                    	     ContextApplication.isEnterprise=true;
	                    	 changeToOKActivity();
                   	     }catch(Exception e){}
					     break; 
				}
			}
		};
		
		
	private class Task extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			if(params[0].equals(TASK_REGISTER)){
				return doRegiSter();
			}else
			    return ""; 
		} 
		@Override
		protected void onPostExecute(String result) {				
			super.onPostExecute(result);

			if(result.equals("register_fail")){
				Message msg = Message.obtain();
				msg.what = RESULT_REGISTER_FAIL;
				handler.sendMessage(msg);
			}else if(result.equals("register_ok")){
				Message msg = Message.obtain();
				msg.what = RESULT_REGISTER_OK;
				handler.sendMessage(msg);
			}else if(result.equals("register_had")){
				Message msg = Message.obtain();
				msg.what = RESULT_REGISTER_HAD;
				handler.sendMessage(msg);
			}
		} 
		@Override
		protected void onPreExecute() { 
			super.onPreExecute(); 
			Message msg = Message.obtain();
			msg.what = ALERT_LOADING;
			handler.sendMessage(msg);
			 
		} 
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
		}
	}
    
    
}